package com.hl.card.credit.pub.pager;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

//import com.mongodb.BasicDBObject;
//import com.mongodb.DBObject;

/**
 * 
 * <p>
 * <ol style='font-size:12px'>
 * <li>
 * Describe ：</li>
 * <li>Write date ：2011-9-7</li>
 * <li>
 * Developer ：<a href='MailTo:abc-127@qq.com' title='Send to the E-mail'>English
 * name is Fd wang</a></li>
 * <li>Company ：</li>
 * </ol>
 * </p>
 */
public class Pager implements Cloneable{

	private int curPage = 1; // 当前页
	private int rowCount = 0; // 总行数
	private int pageSize = 10; // 页大小
	private int pageCount = 0; // 总页数
	private int pageOffset = 0;// 当前页起始记录
	private int pageTail = 0;// 当前页到达的记录
	private int pageSkipNum= -1;// 多表时 查第二张表跳过的记录数
	
	public Pager clone() {   
        try {   
            return (Pager) super.clone();   
        } catch (CloneNotSupportedException e) {   
            return null;   
        } 
 }
	/**
	 * 多字段排序
	 */
	private String sortArr;
	
	/**
	 * 排序方式 : desc(倒序) or asc（顺序）
	 */
	private String order; 
	
	/**
	 * 排序字段
	 */
	private String sort; 
	
	/**
	 * 默认为分页
	 */
	private Boolean pagination = true;


	public Pager() {
//		this.orderDirection = true;
	}
	
	public int getPageTotal(int totalCount){
		int pageTotal=totalCount/this.pageSize+1;
		if( totalCount % this.pageSize==0)
			pageTotal--;
		return pageTotal;
	}

	protected void doPage() {
		this.pageCount = this.rowCount / this.pageSize + 1;
		// 如果模板==0，且总数大于1，则减一
		if ((this.rowCount % this.pageSize == 0) && pageCount > 1)
			this.pageCount--;
		if(curPage < 1){
			curPage = 1;
		}
		// Mysql 算法
		this.pageOffset = (this.curPage - 1) * this.pageSize;
		this.pageTail = this.pageOffset + this.pageSize;
		if ((this.pageOffset + this.pageSize) > this.rowCount)
			this.pageTail = this.rowCount;
	}

	/**
	 * 多字段排序
	 * 后续扩展方向 ，验证字段是否存在与类中或者表中
	 * 
	 * @return
	 */
	public String getSortArrSQL(){
		StringBuilder sb=new StringBuilder("");
		if(StringUtils.isNotBlank(sortArr)){
			String[] arr=sortArr.split(",");
			if(arr.length>0){
				for (int i = 0; i < arr.length; i++) {
					String[] node=arr[i].split(":");
					if(node.length!=2){
						node[1]="asc";
					}
					if(!("desc".equals(node[1].trim().toLowerCase()) || "asc".equals(node[1].trim().toLowerCase()))){
						node[1]="asc";
					}
					if(i==0)
						sb.append("order by "+node[0]+" "+node[1]);
					else
						sb.append(","+node[0]+" "+node[1]);
				}
			}
		}
		return sb.toString();
	}

	
	/**
	 * 返回排序字符串  order by id desc;
	 * @return
	 */
	public String getOrderSQL(){
		if(StringUtils.isNotBlank(sort)){
			return  " order by " + sort + " "+getOrder();
		}else if(StringUtils.isNotBlank(sortArr)){
			return getSortArrSQL();
		}
		return "";
	}
	
	/**
	 * 排序方式 : desc(倒序) or asc（顺序）</br>默认为：asc（顺序）
	 * @return
	 */
	private String getOrder() {
		if(order == null || order == ""){
			return "asc";
		}
		if("desc".equals(order.trim().toLowerCase()) || "asc".equals(order.trim().toLowerCase())){
			return order;
		}
		return "asc";
	}

	/**
	 * 获取分页SQL
	 * @return
	 */
	public String getLimitSQL() {
		String condition = "";
		if(pageSize>0 && pagination){
			condition = " limit " + pageOffset + "," + pageSize;
		}
		return condition;
	}
 
	
	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getPageCount() {
		return pageCount;
	}


	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		if (curPage<1) {
			this.curPage = 1;
		}else {
			this.curPage = curPage;
		}
	}

	public void setPageOffset(int pageOffset) {
		this.pageOffset = pageOffset;
	}

	/**
	 * 当前页起始记录
	 * @return
	 */
	public int getPageOffset() {
		return pageOffset;
	}

	public void setPageSize(int pageSize) {
		/**
		 * 防止前台传值为0*/
		if (pageSize>0) {
			this.pageSize = pageSize;
		}
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageTail(int pageTail) {
		this.pageTail = pageTail;
	}

	/**
	 * 当前页到达的记录
	 * @return
	 */
	public int getPageTail() {
		return pageTail;
	}

	public void setRowCount(int rowCount) {
		this.rowCount = rowCount;
		this.doPage();
	}

	public int getRowCount() {
		return rowCount;
	}

	public Boolean getPagination() {
		return pagination;
	}

	public void setPagination(Boolean pagination) {
		this.pagination = pagination;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public void setSortArr(String sortArr) {
		this.sortArr = sortArr;
	}

	public String getSortArr() {
		return sortArr;
	}
	
	/**
	 * 
	 * @param count 要查询的第一张表符合条件的总数
	 * @return  
	 * 			-1 异常
	 * 			0 查询两张表
	 * 			1 查询第一张表
	 * 			2 查询第二张表
	 * 
	 */
	public int getTalbe(int count) {
		int table = -1;
		// 起始位置
		int off = pageSize * (curPage - 1);
		// 结束位置
		int taill = off + pageSize;

		// 查两张表
		if (count == 0 || count > off && count < taill) {
			table = 0;
		}
		// 查第一张表
		else if (count >= taill) {
			table = 1;
		}
		// 查第二张表
		else if (count < taill) {
			// 取第一张表的分页数
			int s2 = count / pageSize;
			// 跳过的页数
			int m = count % pageSize == 0 ? s2 : s2 + 1;
			// 补全第一张表的整数页条数
			int n = m * pageSize - count;
			pageSkipNum = (curPage - m - 1) * pageSize + n;
			// 补全第一张表整页
			table = 2;
		}
		return table;
	}

	public int getPageSkipNum() {
		return pageSkipNum;
	}

	public Map<String, Object> returnPager(){
		Map<String, Object> map = new HashMap<String, Object>();
			map.put("curPage", curPage); // 当前页
			map.put("rowCount", rowCount); // 总行数
			map.put("pageSize", pageSize); // 页大小
			map.put("pageCount", pageCount); // 总页数
		return map;
	}
	
	@Override
	public String toString() {
		return "Pager [当前页curPage=" + curPage + ", 总行数rowCount=" + rowCount
				+ ", 页大小pageSize=" + pageSize + ", 总页数pageCount=" + pageCount
				+ ", 当前页起始记录pageOffset=" + pageOffset + ", 当前页到达的记录pageTail=" + pageTail
				+ ", 跳过的记录数pageSkipNum=" + pageSkipNum + ", 多字段排序sortArr=" + sortArr
				+ ", 排序方式order=" + order + ", 排序字段sort=" + sort + ", pagination="
				+ pagination + "]";
	}
	
	/**
	 * mongoDB排序
	 * 后续扩展方向 ，验证字段是否存在与类中或者表中
	 * 
	 * @return
	 */
	/*
	public DBObject getSortArrMongo() {
		BasicDBObject sortDB = new BasicDBObject();
		if (StringUtils.isNotBlank(sortArr)) {
			System.out.println("分页属性sortArr：" + sortArr);
			String[] sortArrs = sortArr.split(",");
			for (int i = 0; i < sortArrs.length; i++) {
				String[] s = sortArrs[i].split(":");
				if (s.length > 0) {
					String key = s[0];
					int value = 1;
					if (s.length == 2) {
						if ("desc".equals(s[1].toLowerCase().trim())) {
							value = -1;
						}
						sortDB.put(key, value);
					}
				}
			}
		}
		if (StringUtils.isNotBlank(sort)) {
			String key = sort;
			int value = 1;
			if (StringUtils.isNotBlank(order)) {
				System.out.println("分页属性order：" + order);
				if (("desc".equals(order.toLowerCase().trim()))) {
					value = -1;
					System.out.println("value=：" + value);
				}
				sortDB.put(key, value);
			}
		}
		System.out.println("排序参数：" + sortDB.toString());
		return sortDB;

	}
*/
	/**
	 * 20160812新增
	 * @param pageSkipNum
	 */
	public void setPageSkipNum(int pageSkipNum) {
		this.pageSkipNum = pageSkipNum;
	}
	
}
